package com.zmn.oms.business.impl.operation;

import com.google.common.collect.Lists;
import com.vdurmont.emoji.EmojiParser;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.business.interfaces.operation.OrderOperationBService;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.model.entity.operation.OrderOperation;
import com.zmn.oms.services.interfaces.operation.OrderOperationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：
 *
 * @author yule
 * @date 2020/12/20 12:18
 */
@Slf4j
@Service
public class OrderOperationBServiceImpl implements OrderOperationBService {
    @Autowired
    private OrderOperationService orderOperationService;
    @Resource
    private RedisManager redisManager;

    /**
     * 新增或修改
     *
     * @param orderOperation
     * @return
     */
    @Override
    public int insertOrUpdateByKey(OrderOperation orderOperation) {
        // region 表情符号转换为字符
        if (StringUtil.isNotBlank(orderOperation.getQuotationName())) {
            orderOperation.setQuotationName(EmojiParser.parseToAliases(orderOperation.getQuotationName()));
        }
        if (StringUtil.isNotBlank(orderOperation.getCreater())) {
            orderOperation.setCreater(EmojiParser.parseToAliases(orderOperation.getCreater()));
        }
        // endRegion

        // 报价人类型为空，报价时间则对应置空
        if (NumberUtil.isNullOrZero(orderOperation.getQuotationType())) {
            orderOperation.setQuotationTime(null);
        }

        OrderOperation operation = orderOperationService.findBykey(orderOperation.getOrderId());
        // 组装参与报价人信息
        if (Objects.nonNull(operation) && StringUtils.isNotBlank(operation.getPartakeQuotationTypes())) {
            String quotationTypeStr = operation.getPartakeQuotationTypes();
            // 字符串转list
            List<Integer> listIds = Arrays.asList(quotationTypeStr.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
            // 报价人不为空
            if (NumberUtil.isNotNullOrZero(orderOperation.getQuotationType())) {
                // 追加参与报价人信息
                listIds.add(orderOperation.getQuotationType());
                // 对参与报价人去重
                List<Integer> newlistIds = listIds.stream().distinct().collect(Collectors.toList());
                // 去括号格式化字符串存储参与报价人信息 eg:  1,2,3
                String partakeQuotationTypes = newlistIds.stream().map(r -> r.toString()).collect(Collectors.joining(","));
                orderOperation.setPartakeQuotationTypes(partakeQuotationTypes);
            }
        }

        // 参与报价人为空，则补全参与报价人信息和首次报价人信息
        if (Objects.nonNull(operation) && StringUtils.isBlank(operation.getPartakeQuotationTypes()) && NumberUtil.isNotNullOrZero(orderOperation.getQuotationType())) {
            orderOperation.setPartakeQuotationTypes(String.valueOf(orderOperation.getQuotationType()));
            // 设置第一次报价人信息
            orderOperation.setFirstQuotationId(orderOperation.getQuotationId());
            orderOperation.setFirstQuotationName(orderOperation.getQuotationName());
            orderOperation.setFirstQuotationType(orderOperation.getQuotationType());
            orderOperation.setFirstQuotationTime(Optional.ofNullable(orderOperation.getCreateTime()).orElse(new Date()));
        }

        // 初始化首次报价人信息，第一次报价，报价类型和参与报价人一致
        if (Objects.isNull(operation) && NumberUtil.isNotNullOrZero(orderOperation.getQuotationType())) {
            orderOperation.setPartakeQuotationTypes(String.valueOf(orderOperation.getQuotationType()));
            // 设置第一次报价人信息
            orderOperation.setFirstQuotationId(orderOperation.getQuotationId());
            orderOperation.setFirstQuotationName(orderOperation.getQuotationName());
            orderOperation.setFirstQuotationType(orderOperation.getQuotationType());
            orderOperation.setFirstQuotationTime(Optional.ofNullable(orderOperation.getCreateTime()).orElse(new Date()));
        }

        // 系统报价和后台报价--归属为确认报价，进行保存确认标示
        List operates = Lists.newArrayList(GlobalConsts.OPERATE_USER_TYPE_SYSTEM, GlobalConsts.OPERATE_USER_TYPE_STAFF);
        boolean haveConfirmQuotation = operates.contains(orderOperation.getQuotationType()) || Objects.equals(Boolean.TRUE, orderOperation.getAddOrderQuotation());
        if (haveConfirmQuotation) {
            String redisKey = String.format(RedisKeyConsts.USER_HAVE_CONFIRM_QUOTATION_KEY, String.valueOf(orderOperation.getOrderId()));
            if (!redisManager.exists(redisKey)) {
                // 由于单子不知道什么时候能完成，固在redis保存设置失效时间，默认为90天，工单取消和完成后自动删除
                redisManager.setex(redisKey, DateUtil.getNowFormatted(), 3600 * 24 * 90);
            }
        }
        return orderOperationService.insertOrUpdateByKey(orderOperation);
    }

}
